# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

### 设备  device management

from builtins import print
from datetime import date

# from msilib import datasizemask
# from time import process_time, time
from tkinter import E
from tkinter.tix import ExFileSelectBox
from flask import Blueprint
from flask import request
import utils.pgsql.pgdevice as device
import utils.pgsql.pgcase as case
import utils.pgsql.pgactivity as activety
from utils.wraps import token, urlcost
import utils.message.response as response
import json
import utils.common.func as func
import requests
import utils.pgsql.pgannualfee
import utils.common.httpclient as httpclient
import time
import utils.common.log as log
import utils
from urllib.parse import urlparse
import utils.pgsql.base.pgconn as pgconn

device_module = Blueprint("base_device", __name__, url_prefix="/api/v1/scenic/device")

#获取所有设备
@device_module.route("/devicefind", methods=["GET"])
def devicefind():
    obj = device.PgDevice()
    res = obj.all()

    return response.make_response_success(res)

# 2.获取admin下面的所有景区的设备
@device_module.route("/admin/<int:adminId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def area_all_admin(adminId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = device.PgDevice()
 
    res = ""
    if userInfo["role"] == 1:
        res = obj.all()
    elif userInfo["role"] == 2:
        res = obj.allByOperator(userInfo["operatorId"])
    elif userInfo["role"] == 3:
        res = obj.allByCase(userInfo["caseId"])

    elif userInfo["role"] == 6:
        all_case = obj.all()
        obj_admin = utils.pgsql.pgadmin.PgAdmin()
        case_list = obj_admin.get_city_cases(adminId)['caseName']
        res = [i for i in all_case if i['caseName'] in case_list]

    # 根据景区AI走向


    # devicestatusinfor = {}
    #  
    # for i in range(len(res)):
    #     try:   
    #         devicestatus = requests.get(
    #             "http://"+ res[i]["svraddr"] + ":80/api/status",
    #             headers={
    #                 "content-type": "application/json",
    #                 "Authorization": "ztdasdasffwadfasdfd",
    #             },
    #         )
    #         res[i]["status"] = json.loads(devicestatus.text)[
    #             "data"][str(res[i]["devicealgoId"])]   
    #     except:
    #         res[i]["status"] = "false"

    #     if res[i]["status"] == True:   
    #         try:
    #             smart = requests.get("http://"+ res[i]["svraddr"] + ":80/ /face/task/" + str(res[i]["devicealgoId"]),
    #                                  headers={
    #                 "content-type": "application/json",
    #                 "Authorization": "ztdasfwadasfasdfasdfd",
    #             },
    #             )
    #             if len(json.loads(smart.text)["data"][0]["rules"][0]["event"]) == 0:
    #                 res[i]["smart"] = "VVV"
    #             else:
    #                 res[i]["smart"] = "CCC"
    #         except:
    #             return response.make_response_1006()
    return response.make_response_success(res)


# to algo  设备数据同步
@device_module.route("/synchronization", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def synchronization():
 
    dev_obj = device.PgDevice()
    ret, res_data = httpclient.synchronization_getdevice()
    if ret:
        for i in range(res_data[-1]["deviceId"]):
            dev_obj.addDevice({"deviceGbCode":""})
        # for i in range(res_data[-1]["caseId"]+1):
        #         dev_obj.delete(i)
        for i in res_data:
            if int(i['states']) == 1:
                i["auditstatus"] ="审核成功"
            dev_obj.addDevice(i)
        return response.make_response_success_no_data()
    else:
        return response.make_response_401()

# 1.获取景区设备--传景区id
@device_module.route("/case/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def device_all_case(caseId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    obj = device.PgDevice()
    res = None
    if userInfo["role"] in [1, 2]:
        if userInfo["role"] == 1 and caseId== 0:# 管理员,查看所有异常设备
            res = obj.get_unnormal_device()
        else:
            res = obj.allByCase(caseId)
    if userInfo["role"] == 3:
        tmp = userInfo['playground_limit']
        res = obj.allByCase(caseId, tmp)
        # for i in range(len(res)):
        #     try:   
        #         devicestatus = requests.get(
        #             "http://"+ res[i]["svraddr"] + ":80/api/status",
        #             headers={
        #                 "content-type": "application/json",
        #                 "Authorization": "ztdasfwadfasdfd",
        #             },
        #         )
        #         res[i]["status"] = json.loads(devicestatus.text)[
        #             "data"][str(res[i]["devicealgoId"])]  
        #     except:
        #         res[i]["status"] = "false"

        #     if res[i]["status"] == True:  
        #         try:
        #             smart = requests.get("http://"+ res[i]["svraddr"] + ":80/api/face/task/" + str(res[i]["devicealgoId"]),
        #                                 headers={
        #                 "content-type": "application/json",
        #                 "Authorization": "ztdasfwadfasdfd",
        #             },
        #             )
        #             if len(json.loads(smart.text)["data"][0]["rules"][0]["event"]) == 0:
        #                 res[i]["smart"] = "vbdfsa"
        #             else:
        #                 res[i]["smart"] = "asdfasd"
        #         except:
        #             return response.make_response_1006()
    if userInfo["role"] in [6]:#城市账号
        res = obj.allByCase(caseId)
    if res or res == []: # 或者查出空数据
        # 额外查下boguan的设备
        obj = case.PgCase()
        case_dic = obj.get(caseId) if caseId!=0 else {}
        if case_dic and 'bg' in case_dic['AIfacilitator']:
            sql = f'select a.*,n."caseName" from tbl_device a left Join tbl_case n on a."caseId"=n."caseId"  where n."dataValid" !=0 and a."states"=\'1\' and a."caseId" ={caseId} order by a."deviceId"'
            res2 = pgconn.boguan_db.exec_fetchall(sql)
            for eq in res2:
                eq['AIstatus'] = True if eq['states'] == 1 else False
            res.extend(res2)
        return response.make_response_success(res)
    return response.make_response_401()

# 3.新增设备
@device_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def device_add():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = device.PgDevice()
        # annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
        deviceInfo = json.loads(request.data)
        # print(deviceInfo)
        res = obj.addDevice(deviceInfo)
        # print(res)  #{'deviceId': 1974}
        
        if res:
            return response.make_response_success(res)
        else:
            return response.make_response_401()

        # if (
        #     obj.get_deviceName(
        #         deviceInfo.get("deviceName"), deviceInfo.get("caseId")
        #     ).get("deviceName")
        #     is not None
        # ):
        #     return response.make_response_1505()
        # try:
        #     algoIdres = requests.get(
        #                 deviceInfo.get("deviceIp")
        #                 + "/api/v1/channel/all",
        #                 headers={
        #                     "content-type": "application/json",
        #                     "Authorization": "ztdasfwadfasdfd",
        #                 }
        #             )
        #     
        #     algoIdres1 = json.loads(algoIdres.text)
        #     for i in algoIdres1["data"]:
        #         if i["rtsp"] == deviceInfo["streamType"]:
        #             return response.make_response_1511()
        # except:
        #     return response.make_response_1006()
        #  
        # if deviceInfo["state"] == "0":
        #         res = obj.addDevice(deviceInfo)
        #         return response.make_response_success_no_data() 
        # else:
        #     
        #     res = obj.addDevice(deviceInfo)
        #     url = "http://127.0.0.1:33033/api/v1/scenic/device/smart/add"
        #     header = {
        #         "content-type": "application/json",
        #     }
        #     dic = {
        #         "deviceIp": deviceInfo["deviceIp"],
        #         "deviceName":deviceInfo["deviceName"],
        #         "streamType": deviceInfo["streamType"],
        #         "deviceGbCode": deviceInfo["deviceGbCode"],
        #         "deviceId":res["deviceId"]
        #     }
        #     ret = requests.post(url, headers=header, data=json.dumps(dic), timeout=5)
        #     ret = json.loads(ret.text)
        #     if ret[0] == "True":
        #         return response.make_response_success(res)
        #     else:
        #         obj.delete(res["deviceId"])
        #         if ret[1] == "1006":
        #             return response.make_response_1006()
        #         elif ret[1] == "1007":
        #             return response.make_response_1007()

    else:
        return response.make_response_401()


# to algo
@device_module.route("/caseone/<int:caseId>", methods=["GET"])
@urlcost.cost_count_wraps
def device_one_case(caseId):

    obj = device.PgDevice()
    res = obj.allByCase(caseId)
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()

# to algo
@device_module.route("/deviceall", methods=["GET"])
@urlcost.cost_count_wraps
def device_caseall():

    obj = device.PgDevice()
    res = obj.allinfoget()
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()


# @device_module.route("/smart/add", methods=["POST"])
# # def smart_add():
#     """
#     algo add
#     """
#     # 鉴权
#     obj = device.PgDevice()
#     deviceInfo = json.loads(request.data)
#     try:
#         algoIdres = requests.get(
#             deviceInfo.get("deviceIp")
#             + "/api/v1/channel/all",
#             headers={
#                 "content-type": "application/json",
#                 "Authorization": "ztdasfwadfasdfd",
#             }
#         )
#         algoIdres1 = json.loads(algoIdres.text)
#         for i in algoIdres1["data"]:
#             if i["rtsp"] == "":
#                 deviceInfo["devicealgoId"] = i["id"]
#                 break
#     except:
#         return json.dumps(["False","1006"])

#     data = {
#         "bit": 0,
#         "encoding": "",
#         "firmwareversion": "",
#         "flv": "",
#         "fps": 0,
#         "gop": 0,
#         "hardwareid": "",
#         "hls": "",
#         "id": deviceInfo["devicealgoId"],
#         "manufacturer": "",
#         "model": "",
#         "name": deviceInfo["deviceName"],
#         "port": 0,
#         "profile": "0",
#         "pwd": "",
#         "quality": 0,
#         "ratio": "",
#         "rtmp": "",
#         "rtsp": deviceInfo["streamType"],
#         "serialnumber": "",
#         "state": 0,
#         "transport_type": "tcp",
#         "url": "",
#         "username": "",
#         "gbcode": deviceInfo["deviceGbCode"]
#     }
#     try:
#
#         requests.post(
#             deviceInfo.get("deviceIp")
#             + "/api/v1/channel/"
#             + str(deviceInfo["devicealgoId"]),
#             json.dumps(data),
#             headers={
#                 "content-type": "application/json",
#                 "Authorization": "ztdasfwadfasdfd",
#             },
#         )
#         # annualobj.modify(
#         #     uniqueCode,
#         #     {"activation": 1, "deviceId": res["deviceId"]},
#         #     "uniqueCode",
#         # )
        
#         res1 = obj.modify(int(deviceInfo["deviceId"]),{"devicealgoId":deviceInfo["devicealgoId"]})
#         return json.dumps(["True","0"])
#     except:
#         return json.dumps(["False","1006"])

@device_module.route("/<int:deviceId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def device_get(deviceId):

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = device.PgDevice()
        return response.make_response_success(obj.get(deviceId))
    else:
        return response.make_response_401()

# 4.编辑设备
@device_module.route("/<int:deviceId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def device_put(deviceId):

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = device.PgDevice()
        dic = json.loads(request.data)
        # deviceIp = "http://"+ str(obj.get(deviceId).get("svraddr"))+":"
        # if dic["state"] == "0" :
        #     dic["devicealgoId"] = -1
        #     try:
        #         algoIdres = requests.get(
        #                     deviceIp
        #                     + "/api/v1/channel/all",
        #                     headers={
        #                         "content-type": "application/json",
        #                         "Authorization": "ztdasfwadfsafadfasdfd",
        #                     }
        #                 )
        #         
        #         algoIdres1 = json.loads(algoIdres.text)
                
        #         for i in algoIdres1["data"]:
        #             if i["gbcode"] == dic["deviceGbCode"]:
        #                 url = "http://127.0.0.1:33033/api/smart/" + str(deviceId)
        #                 header = {
        #                     "content-type": "application/json",
        #                 }
        #                 ret = requests.get(url, headers=header, timeout=5)
        #                 ret = json.loads(ret.text)["data"]["data"][0]
        #                 del ret["id"]
        #                 obj.modify(deviceId, {"isfparams":json.dumps(ret)})
        #                 requests.delete(
        #                     deviceIp + "/api/v1/channel/" + str(i["id"]),
        #                     headers={
        #                         "content-type": "application/json",
        #                         "Authorization": "ztdasfwadfasdfd",
        #                     },
        #                 )
        #                 break
        #     except:
        #         return response.make_response_1006()
        # else:
        #     if  (dic["devicealgoId"]==-1 or dic["devicealgoId"]==""):
        #         url = "http://127.0.0.1:33033/api/device/smart/add"
        #         header = {
        #             "content-type": "application/json",
        #         }
        #         dic1 = {
        #             "deviceIp": deviceIp,
        #             "deviceName":dic["deviceName"],
        #             "streamType": dic["streamType"],
        #             "deviceGbCode": dic["deviceGbCode"],
        #             "deviceId":str(deviceId)
        #         }
        #         ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=5)
        #         ret = json.loads(ret.text)
        #         if ret[0] == "False":
        #             if ret[1] == "1006":
        #                 return response.make_response_1006()
        #             elif ret[1] == "1007":
        #                 return response.make_response_1007()
        #         else:
        #             del dic["devicealgoId"]
        #             url = "http://127.0.0.1:33033/api/device/smart/" + str(deviceId)
        #             header = {
        #                 "content-type": "application/json",
        #             }
        #             dic1 = {
        #                 "facedetection": dic["isfparams"]["rules"][0]["event"],
        #                 "points":dic["isfparams"]["rules"][0]["points"],
        #                 "vlogdata": dic["isfparams"]["params"],
        #             }
        #             ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=30)
        #             ret = json.loads(ret.text)
                    
        # del dic["isfparams"]
        # print("编辑设备",dic)
        if obj.modify(deviceId, dic):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()

# 5.删除设备_设备id
@device_module.route("/<int:deviceId>", methods=["DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def device_delete(deviceId):

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = device.PgDevice()
        # 查询对应的推流地址 streamType

        streamPath_dic = obj.get(deviceId)
        streamPath_str = streamPath_dic.get("streamType",'')
        # print("streamPath_str",streamPath_str)
        AI_del_streamPath = post_del_streamPath(streamPath_str)
        if not AI_del_streamPath:
            # 删除失败
            return response.make_response_1000()

        if obj.delete(deviceId):
                return response.make_response_success_no_data()
        else:
            return response.make_response_1000()

    else:
        return response.make_response_401()


# 1.获取景区项目--传项目id
@device_module.route("/playground", methods=["GET"])
@urlcost.cost_count_wraps
def all_playground():
    # userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    case_id = request.args.get('caseId') if request.args.get('caseId') else None
    # if userInfo["role"] in [1, 2, 3]:
    obj = case.PgCase()
    res = obj.get_playground(case_id)
    for i in res:
        i['ai_ip'] = i['ai_ip'].strip()
    return response.make_response_success(res)
    # else:
    #     return response.make_response_401()

@device_module.route("/playground/create", methods=["POST", "PUT"])
@token.login_required
@urlcost.cost_count_wraps
def playground_create_or_update():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    res = ""
    if userInfo["role"] in [1]:
        dic = json.loads(request.data)
        obj = case.PgCase()
        if not dic['id']: #新建
            dic.pop('id')
            res = obj.create_playground(dic)
        else:    #更新
            keys = ['case_id', 'name', 'ai_ip']
            rdata = {k: dic[k] for k in keys}
            res = obj.update_playground(rdata, 'id', dic['id'])
    if res:
        return response.make_response_success(res)
    else:
        return response.make_response_401()


@device_module.route("/playground/delete", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def playground_delete():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    res = ""
    if userInfo["role"] in [1]:
        dic = json.loads(request.data)
        obj = case.PgCase()
        if dic['id']:  # 新建
            res = obj.delete_playground(dic['id'])
    if res:
        return response.make_response_success(res)
    else:
        return response.make_response_401()


# @device_module.route("/smart/delete", methods=["POST"])
# def algo_delete():
#     deviceIp = json.loads(request.data)["deviceIp"]
#     devicealgoId = json.loads(request.data)["devicealgoId"]
#     try:
#         requests.delete(
#             deviceIp + "/api/v1/channel/" + str(devicealgoId),
#             headers={
#                 "content-type": "application/json",
#                 "Authorization": "ztdasfwadfasdfd",
#             },
#         )

#         return response.make_response_success_no_data()
#     except:
#         return response.make_response_1006()


# @device_module.route("/smart/<int:deviceId>", methods=["POST"])
# # @token.login_required
# # @urlcost.cost_count_wraps
# def smart_put(deviceId):
#     """
#     algo samrt 
#     """
#      
#     time.sleep(2)
#     smartInfo = json.loads(request.data)
#     obj = device.PgDevice()
#     devicealgoId = obj.get(deviceId).get("devicealgoId")
#   
#     deviceIp = "http://"+ str(obj.get(deviceId).get("svraddr"))+" "

#     if len(smartInfo["points"]) == 0:
#         smartInfo["points"] = [
#             {"xadf": "0", "yasdf": "0"},
#             {"xdasf": "0", "yasdf": "1"},
#             {"xasdf": "1", "yasfd": "1"},
#             {"xasdf": "1", "yasdf": "0"},
#         ]

#     try:
#         data = {
#             "params": {
#                 "maxsize": {
#                     "height": 1920,
#                     "width": 1080,
#                 },
#                 "minsize": {
#                     "height": 20,
#                     "width": 20,
#                 },
#                 "vlogdata": smartInfo["vlogdata"],
#             },
#             "rules": [
#                 {
#                     "event": smartInfo["facedetection"],
#                     "id": 0,
#                     "points": smartInfo["points"],
#                     "type": "polygon",
#                 }
#             ],
#         }
#         smart = requests.put(
#             deviceIp + "/api/v1/smart/config/face/task/" + str(devicealgoId),
#             json.dumps(data),
#             headers={
#                 "content-type": "application/json",
#                 "Authorization": "ztdasfwadfasdfd",
#             },
#         )
#         return response.make_response_success_no_data()
#     except:
#         return response.make_response_1006()


# @device_module.route("/smart/<int:deviceId>", methods=["GET"])
# # @token.login_required
# # @urlcost.cost_count_wraps
# def smart_statu(deviceId):
#     """
#     algo
#     """
#     obj = device.PgDevice()
#     devicealgoId = obj.get(deviceId).get("devicealgoId")
#     deviceIp = "http://"+ str(obj.get(deviceId).get("svraddr"))+":80"
#     
#     try:
#        
#         smart = requests.get(
#             deviceIp + "/api/face/task/" + str(devicealgoId),
#             headers={
#                 "content-type": "application/json",
#                 "Authorization": "ztdasfwaasdf asfd dfasdfd",
#             },
#         )
#         return response.make_response_success(json.loads(smart.text))
#     except:
#         
#         return response.make_response_1006()


'''
接收参数，更新设备数据库设备在线状态 streamStateNotify
'''
#
# @device_module.route("/streamStateNotify", methods=["POST"])
# def streamStateNotify():
#
#     device_data_dic = json.loads(request.data)
#     log.logging.info("streamStateNotify" + str(device_data_dic))
#     # 判断返回的数据类型
#     if not isinstance(device_data_dic,dict):
#         return response.make_response_405()
#     # 判断字段是否存在
#     streamType_str = device_data_dic.get("streamType","")
#     states_str = device_data_dic.get("states","")
#     flvState_str = device_data_dic.get("flvState",False)
#
#     if not streamType_str or not states_str:
#         return response.make_response_1000()
#     # 连接数据库
#     obj = device.PgDevice()
#
#     # 查询当前 数据 是否存在
#     select_res = obj.get_streamType(streamType_str)
#     # print("select_res",select_res)
#     if not select_res:
#         return response.make_response_1000()
#
#     # 更新数据库中字段
#     AIstatus = 'false'
#     flvState = False
#
#     if states_str in [1,"1",2,"2"]:  # （0，等待发布，1，正在发布，2等待关闭，3，关闭不可使用）
#         AIstatus ='true'
#     if flvState_str in ["true",True]:
#         flvState = True
#
#     state_dic ={"AIstatus":AIstatus,"flvState":flvState}
#     updata_res = obj.upda_status(streamType_str,state_dic)
#     # print("updata_res",updata_res)
#     if updata_res:
#         return response.make_response_success_no_data()
#     else:
#         return response.make_response_1000()


@device_module.route("/streamStateNotify", methods=["POST"])
def streamStateNotify():
    device_data_dic = json.loads(request.data)
    log.logging.info("streamStateNotify" + str(device_data_dic))
    # 判断返回的数据类型
    if not isinstance(device_data_dic,dict):
        return response.make_response_405()
    # 判断字段是否存在
    streamType_str = device_data_dic.get("streamType","")
    states_str = device_data_dic.get("states","")
    flvState_str = device_data_dic.get("flvState")

    # 连接数据库
    obj = device.PgDevice()
    # 查询当前 数据 是否存在
    select_res = obj.get_streamType(streamType_str)
    if not select_res:
        return response.make_response_1000()

    # 在线状态 -- 切片可能在可能不在
    if states_str in [1,"1",2,"2"]:  # （0，等待发布，1，正在发布，2等待关闭，3，关闭不可使用）
        AIstatus = 'true'
        # 在线无切片状态
        if flvState_str =="":
            state_dic ={"AIstatus":AIstatus}
        # 在线有切片状态
        else:
            state_dic = {"AIstatus": AIstatus, "flvState": flvState_str}
        updata_res = obj.upda_status(streamType_str,state_dic)
        # print("updata_res",updata_res)
        if updata_res:
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()

    # 不在线 -- 判定不切片
    elif states_str in [3,"3"]:
        AIstatus = 'false'
        flvState = False
        state_dic = {"AIstatus": AIstatus, "flvState": flvState}
        updata_res = obj.upda_status(streamType_str,state_dic)
        # print("updata_res",updata_res)
        if updata_res:
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    # 只有切片状态
    elif flvState_str in ["true",True]:
        flvState = True
        AIstatus = 'true'
        state_dic ={"AIstatus":AIstatus,"flvState":flvState}
        updata_res = obj.upda_status(streamType_str,state_dic)
        # print("updata_res",updata_res)
        if updata_res:
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_success_no_data()


'''
获取推流地址
'''
def write_file(str_data):

    filename = '/home/vlog_platform/webapi/scenic/device.txt'
    with open(filename, 'w') as f:
        f.write(str_data)

@device_module.route("/getStreamByInfo", methods=["POST"])
def getStreamByInfo() -> list:
    # 接收参数
    req_dic = json.loads(request.data)
    print("req_dic: ",req_dic)
    # 判断字段是否存在
    info_str = req_dic.get("info","")
    id_str = req_dic.get("id","")  # 景区id

    if not info_str or not id_str:
        return response.make_response_405()

    # 发送请求
    # Stream_url = "http://103.234.22.70:7070"
    # 百家云测试地址
    # Stream_url = "http://119.45.238.18:7070"
    Stream_url = "http://119.45.63.226:7070"  # 7

    url = Stream_url + "/api/aip/group/getStreamByInfo"

    header = {
        "content-type": "application/json",
        "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
    }

    log.logging.info(json.dumps(req_dic))
    try:

        ret = requests.post(url, headers=header, data=json.dumps(req_dic),verify=False)
   #      retdic = {
   # 	"code": 200,
   # 	"data": "rtmp://103.234.22.70:8083/main/5c4696ff8da6da988d3342350bc34a20",
	# "id":330199999999,
   # 	"msg": "操作成功"
   # }
        retdic = json.loads(ret.text)
        print("推流地址响应",retdic)
    except Exception as e:
        log.logger.warning("error: {}".format(e))
        return response.make_response_406("请求失败",406)

    if retdic.get("code") == 200:

        # obj = device.PgDevice()
        # # 在 设备表 中插入 	groupld 字段  设备未添加需要手动写库
        # groupId = retdic.get("data",{}).get("groupId")
        # streamPath = retdic.get("data",{}).get("streamPath")
        # updata_res = obj.upda_groupld(id_str, groupId)
        # 将响应体写入文件
        write_file(str(retdic))

        return response.make_response_success(retdic.get("data",""))

    else:
        log.logger.error("*****vidoclip query job failed {}".format(retdic))
        return response.make_response_406(str(retdic), 406)


# 11.[ai]获取景区下设备状态
@device_module.route("/device_apply/case/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def device_all_states_case(caseId):
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = device.PgDevice()
        res = obj.allstatesCase(caseId)
        # 有些老的boguan项目，需要查boguan接口
        case_dic = case.PgCase().get(caseId) if caseId != 0 else {}
        if case_dic and "AIfacilitator" in case_dic:
            url = f"https://intelligent.bresee.cn/webapi/v1/scenic/device_apply/case/{caseId}"
            try:
                r1 = requests.get(url,timeout=2)
                data = r1.json()
                if data and "data" in data:
                    res.extend(data['data'])
            except requests.exceptions.Timeout:
                pass
        return response.make_response_success(res)
    else:
        return response.make_response_401()



# 修改 设备 上线下线状态
@device_module.route("/device_states/", methods=["POST"])
@token.login_required
def POST_device_states():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    dic = json.loads(request.data)
    print("dic",dic)
    def add_blacklist(streampath):
        parserd = urlparse(streampath)
        url = f"http://{parserd.hostname}:8081/api/addblacklist?streamPath={parserd.path.lstrip('/')}"
        res = requests.put(url)
        return res.text
    def del_blacklist(streampath):
        parserd = urlparse(streampath)
        url = f"http://{parserd.hostname}:8081/api/delblacklist?streamPath={parserd.path.lstrip('/')}"
        res = requests.put(url)
        return res.text
    if userInfo["role"] in [1,0]:
        obj = device.PgDevice()
        streampath = dic['streamType']
        if dic["states"] == '0':# 0 下线, 1 上线
            res = add_blacklist(streampath)
            return response.make_response_success_tech({"res":res})
        if dic["states"] == '1':# 0 下线, 1 上线
            res = del_blacklist(streampath)
            return response.make_response_success_tech({"res":res})
        # if obj.update_auditstatus_State(dic["auditstatus"],dic["states"], dic["deviceId"]):
        #     resp = response.make_response_success_no_data()
        #     # resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
        #     # resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
        #     return resp
        return response.make_response_1000()
    else:
        return response.make_response_401()


# 获取流的黑名单
@device_module.route("/stream_blacklist", methods=["POST"])
@token.login_required
def stream_blacklist():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    dic = json.loads(request.data)
    print("dic",dic)
    if userInfo["role"] in [1,0]:
        obj = device.PgDevice()
        if obj.update_auditstatus_State(dic["auditstatus"],dic["states"], dic["deviceId"]):
            resp = response.make_response_success_no_data()
            # resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
            # resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
            return resp
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()



'''请求算法删除对应推流地址，释放资源'''
def post_del_streamPath(streamPath):
    """
    :param streamPath: 
    :return: 
    """
    # 发送数据给AI
    # 根据流媒体中ip查询对应平台ip
    _url = urlparse(streamPath)
    hostname_ip = _url.hostname
    # 根据流媒体查平台ip
    obj = device.PgDevice()
    streamPath_dic = obj.get_server_ip(hostname_ip)
    ExternalIp_str = streamPath_dic.get("ExternalIp", '')
    log.logging.info(hostname_ip)
    log.logging.info(streamPath_dic)
    Stream_url = f"http://{ExternalIp_str.strip()}:7070"
    url = Stream_url + "/api/aip/group/delStream"
    header = {
        "content-type": "application/json",
        "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
    }
    send_delStream_dic = {"streamPath":streamPath}
    log.logging.info(Stream_url)
    log.logging.info(send_delStream_dic)

    try:
        ret = requests.post(url, headers=header, data=json.dumps(send_delStream_dic), verify=False)

        retdic = json.loads(ret.text)
        print("删除推流地址", retdic)  # {"code": 200,"msg": "操作成功！","data": null}
    except Exception as e:
        return False
    status_num = retdic.get("code", 0)
    if status_num in [200, "200",400,"400"]:
        return True
    else:
        # {'code': 400, 'msg': '未查询到流地址', 'data': None}
        if f"{status_num}" == "400" and retdic.get('retdic.get') == "未查询到流地址":
            # 流不存在，直接删
            return True
        return False




# 批量生成推流地址
@device_module.route("/streamPathList", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def streamPathList():
    # 接收参数
    req_dic = json.loads(request.data)
    info_str = req_dic.get("info", "")
    count_num = req_dic.get("count", "")
    serverIp = req_dic.get("serverIp", "")

    if not info_str or not count_num:
        return response.make_response_405()
    return_list =[]
    info_end_str = info_str[-1]
    for i in range(1, count_num + 1):
        send_sic = {"id": 1638}
        # 校验info 结尾为 数字  /  字母
        if info_end_str =="/":
            send_sic["info"] = info_str + "0"+str(i)
        elif info_end_str <"99":
            send_sic["info"] = ''.join(info_str.split("/")[:-1]) + "0" + str(i)
        else:
            send_sic["info"] = info_str + "/0"+str(i)

        # 发送请求
        # Stream_url = "http://103.234.22.70:7070"  // 测试地址
        # Stream_url = "http://119.45.238.18:7070"   # 1
        # Stream_url = "http://118.195.226.96:7070"   # 4
        # Stream_url = "http://118.195.136.98:7070"   # 5
        # Stream_url = "http://146.56.237.33:7070"   # 6
        Stream_url = "http://"+serverIp +":7070"   # 7

        url = Stream_url + "/api/aip/group/getStreamByInfo"

        header = {
            "content-type": "application/json",
            "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
        }

        log.logging.info(json.dumps(send_sic))
        try:
            ret = requests.post(url, headers=header, data=json.dumps(send_sic), verify=False)
            retdic = json.loads(ret.text)
#             retdic = {
#     "code": 200,
#     "msg": "操作成功！",
#     "data": {
#         "streamPath": "rtmp://146.56.223.193:1935/shuipiaoliu/16b1420698b9f669fa5136694d1e98e7",
#         "groupId": 65,
#         "id": 1638
#     }
# }

        except Exception as e:
            log.logger.warning("error: {}".format(e))
            return response.make_response_406("请求失败", 406)

        if retdic.get("code") == 200:
            return_list.append(retdic.get("data", ""))

        else:
            log.logger.error("***** streamPathList {}".format(retdic))
            return response.make_response_406(str(retdic), 406)

    return response.make_response_success(return_list)



@device_module.route("/device_apply/case/record_data", methods=["GET"])
def case_record_data():
    casename_list = ['通天河','碧峰峡','泸山','清境桃源','大奇山','十里','长生洞','玉龙溪','独山子','棉花天坑','九皇山','清水江','葡萄沟','黄河三峡','天龙池','太冰沟']
    res_list=[]
    print(casename_list)
    for casename in casename_list:
        obj = device.PgDevice()
        res = obj.get_record(casename)
        res_list.append(res)
    return response.make_response_success(res_list)

@device_module.route("/device_apply/case/unormal_device", methods=["GET"])
def unormal_device():
    obj = device.PgDevice()
    res_list = obj.get_unnormal_device()
    return response.make_response_success(res_list)



